package com.xianyun.site.auth.service.execute;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.BizException;
import com.xianyun.common.core.utils.StringUtils;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.auth.common.config.system.LoginType;
import com.xianyun.site.auth.common.constant.AuthConstant;
import com.xianyun.site.auth.common.exception.ExtendKeyException;
import com.xianyun.site.auth.common.token.IAuthenticationToken;
import com.xianyun.site.auth.service.ISystemUserService;
import com.xianyun.site.iblog.api.user.dubbo.SocialUserEchoService;
import com.xianyun.site.iblog.api.user.dubbo.SystemUserEchoService;
import com.xianyun.site.iblog.dto.user.SocialUserBindCmd;
import com.xianyun.site.iblog.dto.user.SystemUserLoginQry;
import com.xianyun.site.iblog.dto.user.data.SystemUserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.DigestUtils;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class SystemBaseLoginQueryExo {

    @Reference
    private SystemUserEchoService systemUserEchoService;

    @Reference
    private SocialUserEchoService socialUserEchoService;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ISystemUserService systemUserService;

    public UserDetails execute(IAuthenticationToken token){
        if (StringUtils.isNotEmpty(token.getExtendType())){
            SystemUserLoginQry qry=new SystemUserLoginQry();
            qry.setExtendKey(token.getExtendKey());
            qry.setCredentials(token.getCredentials().toString());
            qry.setExtendType(Integer.parseInt(token.getExtendType()));
            qry.setSessionId(token.getRequest().getSession().getId());
            SystemUserDTO systemUserDTO = systemUserEchoService.getUserInfoByConditionsForLogin(qry);
            if ( null != systemUserDTO){
                System.out.println(systemUserDTO);
                SocialUserBindCmd cmd = SocialUserBindCmd.builder()
                        .sessionId(qry.getSessionId())
                        .userId(systemUserDTO.getId().toString())
                        .socialId(qry.getSocialId()).build();
                checkAndBindSocialUser(cmd);
            }
            return systemUserService.initAndQueryUserDetails(systemUserDTO,LoginType.getItem(qry.getExtendType().toString()));
        } else {
            throw new ExtendKeyException();
        }
    }

    private void checkAndBindSocialUser(SocialUserBindCmd cmd){
        String checkKey= cmd.getSessionId()+ AuthConstant.AUTH_LOGIN_BIND_CHECK;
        String securityKey = DigestUtils.md5DigestAsHex(checkKey.getBytes());
        //若三方登录记录存在则 绑定用户和三方账号（并校验是否绑定） 否则Pass
        SystemUserLoginQry redisResult = redisService.getCacheObject(securityKey);
        if ( null != redisResult){
            Response response = socialUserEchoService.bindSocialUserAndUser(cmd);
            if (!response.isSuccess()){
                throw new BizException(response.getErrCode(),response.getErrMessage());
            }
        }
    }
}
